package controller;


import Utils.ConstantUtils;
import Utils.ResponseData;
import entity.SysAccounts;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import service.SysAccountsService;
import vo.SysAccountsVo;

import javax.servlet.http.HttpSession;


/**
 * 登录
 *
 * @author liujh
 * @since 2020-08-10 17:02:22
 */
@Controller
@Slf4j
@RequestMapping(produces = "application/json;utf-8")
public class SysLoginController {
    /**
     * 服务对象
     */
    @Autowired
    private SysAccountsService sysAccountsService;

    @Autowired
    RedisTemplate redisTemplate;


    @RequestMapping(value = "/")
    public String homePage() {
        return "login";
    }


    @RequestMapping(value = "index")
    public String index() {
        return "index";
    }


    /**
     * 登录
     * @param vo
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public ResponseData login(@RequestBody SysAccountsVo vo){
        UsernamePasswordToken token = new UsernamePasswordToken(vo.getAccount(),vo.getPassword());
        try {
            //vo.setRememberMe(1);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            //subject.getSession().setAttribute("sessionId",SecurityUtils.getSubject().getSession().getId());
        } catch (AuthenticationException e) {
            token.clear();
            e.getMessage();
            return ResponseData.success(ConstantUtils.CODE_STATUS_FAIL,"用户或密码错误");
        }
        return ResponseData.success(ConstantUtils.CODE_STATUS_SUCCESS,ConstantUtils.SUCCESS);
    }

    @RequestMapping(value = "logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            subject.logout();
        }
        if (null!=subject.getSession(false)) {
            redisTemplate.delete(subject.getSession().getId());
        }
        return "login";
    }



}